package com.hgcode.wtboot.web.rest;

import com.hgcode.wtboot.service.PdfGenerateService;
import com.hgcode.wtboot.service.dto.Customer;
import com.hgcode.wtboot.service.dto.QuoteItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/api/pdf")
public class PdfResource {

	@Resource
	private PdfGenerateService pdfGenerateService;

	@GetMapping("/export")
	public void  exportPdf(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> data = createTestData();
		ByteArrayInputStream exportedData = pdfGenerateService.exportPdf("quotation", data);
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment; filename=quotation.pdf");
		IOUtils.copy(exportedData, response.getOutputStream());
	}

	private Map<String, Object> createTestData() {
		Map<String, Object> data = new HashMap<>();
		Customer customer = new Customer();
		customer.setCompanyName("Simple Solution");
		customer.setContactName("John Doe");
		customer.setAddress("123, Simple Street");
		customer.setEmail("john@simplesolution.dev");
		customer.setPhone("123 456 789");
		data.put("customer", customer);

		List<QuoteItem> quoteItems = new ArrayList<>();
		QuoteItem quoteItem1 = new QuoteItem();
		quoteItem1.setDescription("Test Quote Item 1");
		quoteItem1.setQuantity(1);
		quoteItem1.setUnitPrice(100.0);
		quoteItem1.setTotal(100.0);
		quoteItems.add(quoteItem1);

		QuoteItem quoteItem2 = new QuoteItem();
		quoteItem2.setDescription("Test Quote Item 2");
		quoteItem2.setQuantity(4);
		quoteItem2.setUnitPrice(500.0);
		quoteItem2.setTotal(2000.0);
		quoteItems.add(quoteItem2);

		QuoteItem quoteItem3 = new QuoteItem();
		quoteItem3.setDescription("Test Quote Item 3");
		quoteItem3.setQuantity(2);
		quoteItem3.setUnitPrice(200.0);
		quoteItem3.setTotal(400.0);
		quoteItems.add(quoteItem3);

		data.put("quoteItems", quoteItems);
		return data;
	}
}
